package address

import (
	"context"
	"strings"

	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserAddressLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 创建UserAddress
func NewCreateUserAddressLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserAddressLogic {
	return &CreateUserAddressLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateUserAddressLogic) CreateUserAddress(
	req *types.CreateUserAddressReq,
	headers *[]*types.Header,
) (resp *types.BaseIDResp, err error) {
	if req.Consignee == nil || req.Mobile == nil || len(strings.TrimSpace(*req.Consignee)) == 0 || len(strings.TrimSpace(*req.Mobile)) == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_CONSIGNEE_REQUIRED)
	}

	if req.DetailedAddress == nil || len(strings.TrimSpace(*req.DetailedAddress)) == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_ADDRESS_REQUIRED)
	}

	if len(req.Geographic) == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_GEOGRAPHIC_REQUIRED)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var geographic []*userclient.UserMetaInfo
	for _, v := range req.Geographic {
		geographic = append(geographic, &userclient.UserMetaInfo{
			Key:   v.Key,
			Label: v.Label,
			Value: v.Value,
		})
	}

	res, err := l.svcCtx.UserRpc.CreateUserAddress(l.ctx, &userclient.UserAddressInfo{
		UserId:          pointy.GetPointer(userId),
		Label:           req.Label,
		Consignee:       req.Consignee,
		Mobile:          req.Mobile,
		DetailedAddress: req.DetailedAddress,
		PostalCode:      req.PostalCode,
		IsDefault:       req.IsDefault,
		Geographic:      geographic,
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseIDResp{
		Id:  res.Id,
		Msg: "新增地址成功",
	}, nil
}
